from django.http import HttpRequest
from functools import wraps
import inspect

from gis.admin import const
from gis.admin.exceptions import ERROR_USER_INVALID_TOKEN, ERROR_PERMISSION_NOT_AUTHORIZED, ERROR_LIST_FUNC_MISS_ARGS
from gis.admin.services import admin_service
from gis.common.exceptions import BizException


def require_login(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        request = args[0]
        assert isinstance(request, HttpRequest)
        if not request.session.get(const.SESSION_USER_KEY):
            raise BizException(ERROR_USER_INVALID_TOKEN)
        else:
            request.user_id = request.session[const.SESSION_USER_KEY]
            request.user = admin_service.get_user_by_id(request.user_id)
            request.session.modified = True
        return func(*args, **kwargs)

    return wrapper


def check_permission(permission_code):
    def decorator(func):
        def wrapper(*args, **kwargs):
            request = args[0]
            request.permission_code = permission_code
            assert isinstance(request, HttpRequest)
            all_permission_codes = admin_service.get_user_all_permission_codes(request.user_id)
            perms = set(permission_code) if isinstance(permission_code, list) else {permission_code}
            if not perms.intersection(all_permission_codes):
                raise BizException(ERROR_PERMISSION_NOT_AUTHORIZED)
            return func(*args, **kwargs)

        return wrapper

    return decorator


def list_func(func):
    """
    定义规范，查询列表方法必须有 page_size,page_no,order_by 参数
    :param func:
    :return:
    """
    func_args = inspect.getfullargspec(func).args
    need_args = ["page_size", "page_no", "order_by"]
    if not set(need_args).issubset(set(func_args)):
        raise BizException(ERROR_LIST_FUNC_MISS_ARGS)
    return func
